﻿using System;
using System.IO;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Noria.Web.MyMSDN.Models;

namespace Noria.Web.Utility
{
    class BackupService
    {
        private static readonly log4net.ILog alog = log4net.LogManager.GetLogger("Noria.Audit");

        private readonly string _root;
        private readonly string _oldData;
        private readonly string _newData;

        public BackupService(HttpContext context)
        {
            _root = context.Server.MapPath("tmp/backup");
            var now = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            _oldData = Path.Combine(_root, now + "_old.gz");
            _newData = Path.Combine(_root, now + "_new.gz");
        }


        /// <summary>
        /// Backup mymsdn database and save the input new data to local disk 
        /// </summary>
        public BackupService Backup(byte[] buffer)
        {
            using (var db = new MmContext())
            {
                var data = db.Categories.Include("Families.Files").ToArray();
                var raw = JArray.FromObject(data).ToString(Formatting.None);
                var binary = GZipHelper.Compress(raw);
                System.IO.File.WriteAllBytes(_oldData, binary);
                alog.InfoFormat("Database has been backed up, file={0}", _oldData);
            }

            System.IO.File.WriteAllBytes(_newData, buffer);
            alog.InfoFormat("New DB has been archived, file={0}", _newData);

            return this;
        }

        /// <summary>
        /// Delete old backup data
        ///  only keep every first day of month and last 7 days
        /// </summary>
        public BackupService HouseKeep()
        {
            foreach (var file in Directory.GetFiles(_root))
            {
                var time = System.IO.File.GetCreationTime(file);

                if (time.Day == 1)
                {
                    // pass
                }
                else if (DateTime.Now - time < new TimeSpan(7, 0, 0, 0))
                {
                    // pass
                }
                else
                {
                    // delete
                    System.IO.File.Delete(file);
                    alog.InfoFormat("Archive has been removed, file={0}", file);
                }
            }

            return this;
        }
    }
}